﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Data;
using Bzure.Security.Permissions;
using Bzure.Security.Principal;
using Bzure.Common.Core;

namespace Bzure.Apps.Security.DataAccess
{
    public class UserBindRepository : RepositoryBase
    {
        static UserBindRepository()
        {
            UserBind entity = new UserBind();
            Type type = entity.GetType();
            AppendDataMap(type, "ID", () => entity.ID);
            AppendDataMap(type, "UserID", () => entity.UserID);
            AppendDataMap(type, "BindID", () => entity.BindID);
            AppendDataMap(type, "BindProvider", () => entity.BindProvider);
            ResultMapDelegate<UserBind> queryMap = UserBind_Map;
            QueryMapContainer[entity.GetType()] = queryMap;
        }
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="contractProvider"></param>
        public UserBindRepository(Bzure.Common.Transactions.ITransactionSupport contractProvider)
            : base(contractProvider)
        {

        }
        /// <summary>
        /// 实体对应数据库中的表
        /// </summary>
        public override string TableName
        {
            get
            {
                return "T_Security_UserBinds";
            }
        }
        /// <summary>
        /// 角色实体数据映射
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static UserBind UserBind_Map(DataReader reader)
        {
            return new UserBind()
            {
                ID = reader.GetString("ID"),
                UserID = reader.GetString("UserID"),
                BindID = reader.GetStringNullable("BindID"),
                BindProvider = reader.GetStringNullable("BindProvider"),
            };
        }
        /// <summary>
        /// 根据绑定获得用户
        /// </summary>
        /// <param name="BindID"></param>
        /// <param name="BindProvider"></param>
        /// <returns></returns>
        public BzureUser GetUserByBind(string BindID, string BindProvider)
        {
            if (BindID.IsNull() || BindProvider.IsNull())
                return default(BzureUser);
            string sql = string.Format("SELECT T_Security_Users.* FROM T_Security_Users, {0} WHERE T_Security_Users.UserID={0}.UserID AND {0}.BindID=@BindID AND {0}.BindProvider=@BindProvider ", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .AddString("BindID", BindID)
                 .AddString("BindProvider", BindProvider)
                .SetMap(UserRepository.BzureUser_Map)
                .AsSingle();
        }

    }
}
